package com.returnsoft.security.eao;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import javax.ejb.LocalBean;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.persistence.TypedQuery;

import com.returnsoft.security.dto.PermissionDto;
import com.returnsoft.security.dto.UserDto;
import com.returnsoft.security.entity.Permission;
import com.returnsoft.security.exception.EaoExcepcion;
import com.returnsoft.security.exception.SecurityExcepcion;

@LocalBean
@Stateless
public class PermissionEao implements Serializable{

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	@PersistenceContext
	private EntityManager em;

	public List<Permission> findAll() throws EaoExcepcion {
		try {
			String query = "SELECT p FROM Permission p";
			TypedQuery<Permission> q = em.createQuery(query, Permission.class);
			List<Permission> permissions = q.getResultList();
			return permissions;
		} catch (Exception e) {
			e.printStackTrace();
			throw new EaoExcepcion(e.getMessage());
		}
	}

	@SuppressWarnings("unchecked")
	public List<PermissionDto> findByUser(Integer userId) throws EaoExcepcion {
		try {
			System.out.println("Ingreso a buscar permisos");
			String query = "SELECT p.id,p.code,p.name " + "FROM Permission p "
					+ "left join p.users u " + "where u.id = :userId";
			Query q = em.createQuery(query);
			q.setParameter("userId", userId);
			List<Object[]> permissionsObject = (List<Object[]>) q.getResultList();
			
			List<PermissionDto> permissionsDto = new ArrayList<PermissionDto>();
			if (permissionsObject!=null && permissionsObject.size()>0) {
				for (Object[] permissionobject : permissionsObject) {
					Integer permissionId = (Integer) permissionobject[0];
					String permissionCode = (String) permissionobject[1];
					String permissionName = (String) permissionobject[2];
					
					PermissionDto permissionDto = new PermissionDto();
					permissionDto.setId(permissionId);
					permissionDto.setCode(permissionCode);
					permissionDto.setName(permissionName);
					permissionsDto.add(permissionDto);
				}
			}
			
			System.out.println("Termino de buscar permisos");
			return permissionsDto;
		} catch (Exception e) {
			e.printStackTrace();
			throw new EaoExcepcion(e.getMessage());
		}
	}

}
